package com.hqully.smartfumehood.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hqully.smartfumehood.common.enums.DeviceEnum;
import com.hqully.smartfumehood.common.enums.ResultEnum;
import com.hqully.smartfumehood.common.exception.ResultException;
import com.hqully.smartfumehood.common.utils.TimeUtil;
import com.hqully.smartfumehood.common.vo.QueryVo;
import com.hqully.smartfumehood.entity.DevError;
import com.hqully.smartfumehood.entity.DevRecord;
import com.hqully.smartfumehood.entity.Device;
import com.hqully.smartfumehood.entity.dto.DeviceDto;
import com.hqully.smartfumehood.mapper.DevErrorMapper;
import com.hqully.smartfumehood.mapper.DevRecordMapper;
import com.hqully.smartfumehood.mapper.DeviceMapper;
import com.hqully.smartfumehood.service.DeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *     设备服务实现类
 * </p>
 * @author liulingyu
 * @date 2022-05-08 14:40
 * @version 1.0
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DevRecordMapper devRecordMapper;


    @Autowired
    private DevErrorMapper devErrorMapper;
    // region 查询相关方法

    @Override
    public PageInfo<DeviceDto> findAllDevice(QueryVo queryVo) {
        PageHelper.startPage(queryVo.getPageNum(),queryVo.getPageSize(),true);

        List<DeviceDto> deviceList = deviceMapper.findAllDevice(queryVo.getQuery());

        PageInfo<DeviceDto> devicePageInfo = new PageInfo<>(deviceList);




        return devicePageInfo;
    }

    @Override
    public long findDeviceCount(QueryVo queryVo) {
        return deviceMapper.findDeviceCount(queryVo.getQuery());
    }

    @Override
    public PageInfo<DeviceDto> findDeviceByStatus(QueryVo queryVo) {

        PageHelper.startPage(queryVo.getPageNum(),
                queryVo.getPageSize(),true);

        List<DeviceDto> deviceList = deviceMapper.findDeviceByStatus((Integer) queryVo.getQuery().get("queryInfo"));



        PageInfo<DeviceDto> devicePageInfo = new PageInfo<>(deviceList);


        return devicePageInfo;
    }

    @Override
    public DeviceDto findDeviceByDid(String did) {
        return deviceMapper.findDeviceByDid(did);
    }

    @Override
    public DeviceDto findDeviceByLabId(String labId) {
        return deviceMapper.findDeviceByLabId(labId);
    }
// endregion

    @Override
    public int addDevice(Device device) {
        return deviceMapper.addDevice(device);
    }

    @Override
    public int deleteDevice(String did) {
        return deviceMapper.deleteDevice(did);
    }

    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateDevice(device);
    }

    @Override
    public int updateStatusById(Integer status, String id) {

        DeviceDto device = deviceMapper.findDeviceByDid(id);

        if (device == null) {
            throw new ResultException(ResultEnum.RESULT_NULL,"该设备不存在");
        }
        if (device.getStatus().equals(DeviceEnum.DEVICE_STATUS_ERROR.getCode())) {

            return DeviceEnum.DEVICE_STATUS_ERROR.getCode();
        }
        if (status.equals(DeviceEnum.DEVICE_STATUS_ERROR.getCode())){
            deviceMapper.updateStatusById(status,id);
            return DeviceEnum.DEVICE_STATUS_ERROR.getCode();
        }
        if (!device.getStatus().equals(status)){
            return deviceMapper.updateStatusById(status,id);
            }


        return DeviceEnum.DEVICE_STATUS_NO_CHANGE.getCode();

    }

    @Override
    public int updateDeviceStatusAndRecordById(Integer status, String id, LocalDateTime time) {
        // 未知原因可能导致更新空气数据时也进入这个方法，暂时打桩，待解决。
        if (id.equals("2085176893")){
            log.info("update Status by id:{},time:{}",id,time);
            return 1;
        }
        Integer deviceStatus = updateStatusById(status, id);

        //从数据库中查询该设备的使用记录
        DevRecord record = devRecordMapper.findInUseByDeviceId(id);

        //如果设备异常，且存在使用记录，则设置该记录状态为异常,不存在则直接返回
        if(deviceStatus.equals( DeviceEnum.DEVICE_STATUS_ERROR.getCode())){
/*
            if (devErrorMapper.findUnProcessedErrorByDeviceId(id) == null) {

                DevError devError = new DevError();
                devError.setDeviceId(id);
                devError.setErrorType("设备异常");
                devError.setOccurTime(time);
                devErrorMapper.addDevError(devError);
*/
            if (record != null){

                record.setStatus(DeviceEnum.DEVICE_STATUS_ERROR.getCode());

                devRecordMapper.updateRecord(record);
            }

                return 1;

        }

        //如果设备状态更新了(开启->关闭/关闭->开启)
        if (deviceStatus.equals(DeviceEnum.DEVICE_STATUS_CHANGE.getCode())){


            //当前设备要更改状态为开启
            if (status.equals(DeviceEnum.DEVICE_STATUS_OPEN.getCode())){

                //若获取到的记录为空，则创建一个使用记录
                if (record == null) {

                    DevRecord devRecord = createDevRecord(id, time);

                    devRecordMapper.addRecord(devRecord);
                }

            }else if (status.equals(DeviceEnum.DEVICE_STATUS_CLOSE.getCode())){

                //若设备更改状态为关闭且记录不为空，则更新结束时间并计算时长
                if (record != null) {

                    String duration = TimeUtil.formatDuration2Seconds(record.getStartTime(), time);

                    record.setEndTime(time);

                    record.setDuration(duration);

                    devRecordMapper.updateRecord(record);
                }
            }
        }

        return 0;
    }

    private DevRecord createDevRecord(String id, LocalDateTime time) {
        DevRecord devRecord = new DevRecord();

        devRecord.setDeviceId(id);

        devRecord.setStartTime(time);

        devRecord.setUsageDate(time.toLocalDate());
        return devRecord;
    }
}
